<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Kalnoy\Nestedset\NodeTrait;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;
    use NodeTrait;

    protected $dateFormat = 'U';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'phone', 'password','avatar_url','reference_amount','shop_amount',
        'ref_code','asset_password','is_baned','reg_ip','login_ip','baned_reason',
        'is_disable_trade','wechat_code','wechat_qrcode_url','bank_card','real_name',
        'bank_name','login_at'
    ];

    public function tradeQueues()
    {
        return $this->hasMany(TradeQueue::class,'user_id','id');
    }

    public function getAvatarUrlAttribute()
    {
        return \Avatar::create($this->name)->toBase64();
    }

    // Rest omitted for brevity
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    public function generateRefCode($length = 6)
    {
        $refCode = \substr(\str_shuffle(\str_repeat(config('profit.refCodeCharacters'), $length)), 0, $length);
        $count = 0;
        if (!\is_null(User::where('ref_code', $refCode)->first())) {
            $count++;
            $refCode = \substr(\str_shuffle(\str_repeat(config('profit.refCodeCharacters'), $length)), 0, $length);
            if ($count == 100) {
                throw new BadRequestHttpException();
            }
        }
        return $refCode;
    }

    protected static function boot()
    {
        parent::boot();
        // 监听模型创建事件，在写入数据库之前触发
        static::creating(function ($model) {
            // 如果模型的 no 字段为空
            if (!$model->ref_code) {
                // 调用 findAvailableNo 生成订单流水号
                $model->ref_code = static::findAvailableNo();
                // 如果生成失败，则终止创建订单
                if (!$model->ref_code) {
                    return false;
                }
            }
        });
    }
    public static function findAvailableNo()
    {
        // 订单流水号前缀
        $prefix = date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 6 位的数字
            $ref_code = str_pad(random(0, 999999), 6, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!static::query()->where('ref_code', $ref_code)->exists()) {
                return $ref_code;
            }
        }
        \Log::warning('find order no failed');

        return false;
    }
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'asset_password','rememberToken'
    ];
}
